<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NEllipsis,
  NFlex,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NPopconfirm, NSelect,
  NSwitch,
  NTag,
  useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import {router} from "@/router";
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

defineOptions({ name: '企业管理' })
const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '企业',
  initForm: {},
  doCreate: api.createCustomers,//接口地址修改
  doUpdate: api.updateCustomers,//接口地址修改
  doDelete: api.deleteCustomers,//接口地址修改
  refresh: () => $table.value?.handlerefresh(),
})

const data = reactive({
  customer_level: [],
  token: getToken(),
  uploadAction: base_path+'api/customers/customers_list/file',
  onLevelData: [],
  selectValue:'',
  show_excel:false,
  show_info:false,
  c_type:[],
  c_status:[],
  fileList1: [],
  fileList2: [],
  fileList3: [],
});


const customRequestMethod1 = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  console.log(data)
  if (data.code === 200) {
    modalForm.value.sfz_z = data.data.url

    message.success('上传成功')
  } else {
    message.error(data.data)
  }
  return file
}

const customRequestMethod2 = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  console.log(data)
  if (data.code === 200) {
    modalForm.value.sfz_f = data.data.url

    message.success('上传成功')
  } else {
    message.error(data.data)
  }
  return file
}


const customRequestMethod3 = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  console.log(data)
  if (data.code === 200) {
    modalForm.value.yyzz = data.data.url

    message.success('上传成功')
  } else {
    message.error(data.data)
  }
  return file
}


function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}


const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

onMounted(() => {
  api.getStatusLevel().then((res) => (data.c_status = res.data))
  $table.value?.handleSearch()
})

//表单规则部分
const addAPIRules = {
  name: [
    {
      required: true,
      message: '请输入会员昵称',
      trigger: ['input', 'blur'],
    },
  ],
  role_id: [
    {
      required: true,
      message: '请选择会员级别',
      trigger: ['blur', 'change'],
      type: 'number',
    },
  ],
}


function show_info(row){
  data.show_info = true
  data.select_customer = row
}

//table表头
const columns = [
  {
    title: '企业名称',
    key: 'qymc',
    align: 'center',
    width: '300',
    fixed: 'left',
  },
  {
    title: '企业税号',
    key: 'qysh',
    align: 'center',
    width: '200',
    ellipsis: { tooltip: true },
  },

  {
    title: '资金缺口',
    key: 'zjqk',
    align: 'center',
    width: '80',
    ellipsis: { tooltip: true },
  },
  {
    title: '法人姓名',
    key: 'name',
    width: '80',
    align: 'center',
  },
  {
    title: '手机号码',
    key: 'phone',
    width: '120',
    align: 'center',
  },
  {
    title: '注册时间',
    key: 'created_at',
    width: '200',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '审批金额',
    key: 'price',
    width: '80',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '归属经理',
    key: 'user_name',
    width: '100',
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '状态',
    key: 'status',
    align: 'center',
    width: 100,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '0px' } },
          { default: () => row.status_name }
      )
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: '200',
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
            h(
                NButton,
                {
                  size: 'small',
                  type: 'primary',
                  style: 'margin-right: 8px;',
                  onClick: () => {
                    handleEdit(row)
                    data.fileList1.value = [{
                        id: 1,
                        name: '封面',
                        url: row.sfz_z,
                        status: "finished"
                      }]
                    data.fileList2.value = [{
                        id: 1,
                        name: '封面',
                        url: row.sfz_f,
                        status: "finished"
                      }]
                    data.fileList3.value = [{
                        id: 1,
                        name: '封面',
                        url: row.yyzz,
                        status: "finished"
                      }]
                  },
                },
                {
                  default: () => '编辑',
                  icon: renderIcon('material-symbols:edit', { size: 16 }),
                }
            ),
            [[vPermission, 'post/api/customers/customers_list/update']]
        ),
        h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete({ id: row.id }, false),
              onNegativeClick: () => { },
            },
            {
              trigger: () =>
                  withDirectives(
                      h(
                          NButton,
                          {
                            size: 'small',
                            type: 'error',
                          },
                          {
                            default: () => '删除',
                            icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                          }
                      ),
                      [[vPermission, 'delete/api/customer/users/delete']]
                  ),
              default: () => h('div', {}, '确定删除该数据吗?'),
            }
        ),
      ]
    },
  },
]

//上传头像
const message = useMessage();

const customRequestMethod = (options) => {
  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        console.log(data, 'datatat');
        if (data.code == 200) {
          modalForm.value.avatar = data.data.url
          message.success('文件上传成功');
          options.onProgress(data);
        }else{
          message.error(data.msg);
        }
      })
};
// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.is_active = row.is_active === false ? true : false
  row.publishing = false
  try {
    await api.updateCustomer(row)
    $message?.success(row.is_active ? '已取消禁用该用户' : '已禁用该用户')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.is_active = row.is_active === false ? true : false
  } finally {
    row.publishing = false
  }
}

async function handleUpdateUser(row) {
  if (!row.id) return
  row.publishing = true
  row.is_user = row.is_user === false
  row.publishing = false
  try {
    await api.updateCustomer(row)
    $message?.success(row.is_user ? '已设置为员工': '已取消')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.is_user = row.is_user === false
  } finally {
    row.publishing = false
  }
}

//获取默认会员类型
async function getcosutomer_level() {
  let ret = await api.getCustomerLevel()
  data.customer_level = ret.data
}

//获取上级部门id
async function onleves(query) {
  let val = await api.getLeves({key:query})
  data.onLevelData = val.data
}

//异步下拉获取上级
const loadingRef = ref(false);
const optionsRef = ref([]);
const handleLeves = (query) => {
  if (!query.length) {
    optionsRef.value = [];
    return;
  }
  onleves(query)
  loadingRef.value = true;
  // data.selectValue
  window.setTimeout(() => {
    data.onLevelData.value = data.onLevelData.filter(
        (item) => ~item.label.indexOf(query)
    );
    loadingRef.value = false;
  }, 1e3);
}

async function  on_excel(){
  await api.onCustomerExcel({start_time:queryItems.value.start_time,end_time:queryItems.value.end_time})
  data.show_excel = true
  //$message?.success('正在生成下载文件,请前往下载中心查看')
}
function go_excel(){
  router.push({ path: '/downloads/list' });
}

</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="企业列表">
<!--    <template #action>-->
<!--      <div>-->
<!--        <NButton v-permission="'get/api/customer/users/excel'" class="float-right" type="primary" @click="on_excel">-->
<!--          <TheIcon icon="material-symbols:timeline" :size="18" class="mr-5" />导出-->
<!--        </NButton>-->
<!--        <NButton  v-permission="'post/api/customer/users/create'"  class="float-right mr-15" type="primary" @click="handleAdd">-->
<!--          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />注册新会员-->
<!--        </NButton>-->
<!--      </div>-->
<!--    </template>-->
    <!-- 表格 -->
    <CrudTable ref="$table" v-model:query-items="queryItems" :columns="columns" :get-data="api.getCustomers"
               :scroll-x="1600" >
      <template #queryBar>
        <QueryBarItem label="公司名称" :label-width="70">
          <NInput v-model:value="queryItems.qymc" clearable type="text" placeholder="请输入公司名称"
                  @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="法人姓名" :label-width="70">
          <NInput v-model:value="queryItems.name" clearable type="text" placeholder="请输入法人姓名"
                  @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
<!--        <QueryBarItem label="手机号码" :label-width="70">-->
<!--          <NInput v-model:value="queryItems.phone" clearable type="text" placeholder="请输入手机号"-->
<!--                  @keypress.enter="$table?.handleSearch()" />-->
<!--        </QueryBarItem>-->
        <!--        <QueryBarItem label="创建时间" :label-width="70">-->
        <!--          <NDatePicker-->
        <!--            v-model:value="datetimeRange"-->
        <!--            type="datetimerange"-->
        <!--            clearable-->
        <!--            placeholder="请选择时间范围"-->
        <!--            @update:value="handleDateRangeChange"-->
        <!--          />-->
        <!--        </QueryBarItem>-->
        <QueryBarItem label="客户状态" :label-width="80">
          <NSelect
              v-model:value="queryItems.status"
              style="width: 150px"
              :options="data.c_status"
              clearable
              placeholder="请选客户状态"
          />
        </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal v-model:visible="modalVisible" :title="modalTitle" :loading="modalLoading"
               style="width: 750px !important;" @save="handleSave">

      <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="120" :model="modalForm"
             :rules="addAPIRules" :validate-on-rule-change="true">
        <n-tabs type="line" animated size="large" :tabs-padding="20" pane-style="padding: 20px;">
          <n-tab-pane name="企业信息">
            <NFormItem label="企业名称" path="qymc">
              <NInput v-model:value="modalForm.qymc" clearable placeholder="企业名称" />
            </NFormItem>
            <NFormItem label="企业税号" path="qysh">
              <NInput v-model:value="modalForm.qysh" clearable placeholder="企业税号" />
            </NFormItem>
            <NFormItem label="资金缺口" path="zjqk">
              <NInput v-model:value="modalForm.zjqk" clearable placeholder="资金缺口" />
            </NFormItem>
            <NFormItem label="2024年开票" path="kp24">
              <NInput v-model:value="modalForm.kp24" clearable placeholder="2024年开票" />
            </NFormItem>
            <NFormItem label="2023年开票" path="kp23">
              <NInput v-model:value="modalForm.kp23" clearable placeholder="2023年开票" />
            </NFormItem>
             <NFormItem label="企业地址" path="address">
              <NInput v-model:value="modalForm.address" clearable placeholder="企业地址" />
            </NFormItem>
          </n-tab-pane>
          <n-tab-pane name="法人信息">
            <NFormItem label="法人姓名" path="name">
              <NInput v-model:value="modalForm.name" clearable placeholder="法人姓名" />
            </NFormItem>
            <NFormItem label="身份证号码" path="sfz">
              <NInput v-model:value="modalForm.sfz" clearable placeholder="身份证号码" />
            </NFormItem>
            <NFormItem label="手机号码" path="phone">
              <NInput v-model:value="modalForm.phone" clearable placeholder="手机号码" />
            </NFormItem>
            <NFormItem label="银行卡号" path="yh_no">
              <NInput v-model:value="modalForm.yh_no" clearable placeholder="银行卡号" />
            </NFormItem>
            <NFormItem label="开户行" path="yh_khh">
              <NInput v-model:value="modalForm.yh_khh" clearable placeholder="开户行" />
            </NFormItem>
            <NFormItem label="预留手机号" path="yh_phone">
              <NInput v-model:value="modalForm.yh_phone" clearable placeholder="预留手机号" />
            </NFormItem>
            <NFormItem label="婚姻状况" path="hyzk">
              <NInput v-model:value="modalForm.hyzk" clearable placeholder="婚姻状况" />
            </NFormItem>
          </n-tab-pane>
            <n-tab-pane name="其他联系人信息">
            <NFormItem label="配偶姓名" path="po_name">
              <NInput v-model:value="modalForm.po_name" clearable placeholder="配偶姓名" />
            </NFormItem>
            <NFormItem label="配偶手机号" path="po_phone">
              <NInput v-model:value="modalForm.po_phone" clearable placeholder="配偶手机号" />
            </NFormItem>
            <NFormItem label="配偶身份证号" path="po_sfz">
              <NInput v-model:value="modalForm.po_sfz" clearable placeholder="配偶身份证号" />
            </NFormItem>
            <NFormItem label="紧急联系人1" path="contact1">
              <NInput v-model:value="modalForm.contact1" clearable placeholder="紧急联系人1" />
            </NFormItem>
            <NFormItem label="紧急联系人2" path="contact2">
              <NInput v-model:value="modalForm.contact2" clearable placeholder="紧急联系人2" />
            </NFormItem>
               </n-tab-pane>
            <n-tab-pane name="证件照片">
              <NFormItem label="法人身份证正面" path="sfz_z" style="width: 100%">
              <n-upload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
                @finish="customRequestMethod1" list-type="image-card" v-model:file-list="data.fileList1.value"
                :show-file-list="true">
              </n-upload>
            </NFormItem>
              <NFormItem label="法人身份证反面" path="sfz_f" style="width: 100%">
              <n-upload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
                @finish="customRequestMethod2" list-type="image-card" v-model:file-list="data.fileList2.value"
                :show-file-list="true">
              </n-upload>
            </NFormItem>
              <NFormItem label="营业执照副本" path="yyzz" style="width: 100%">
              <n-upload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
                @finish="customRequestMethod3" list-type="image-card" v-model:file-list="data.fileList3.value"
                :show-file-list="true">
              </n-upload>
            </NFormItem>
          </n-tab-pane>
          <n-tab-pane name="审批金额">
            <NFormItem label="金额" path="price">
            <NInput v-model:value="modalForm.price" clearable placeholder="金额" />
          </NFormItem>
          </n-tab-pane>
        </n-tabs>

      </NForm>

    </CrudModal>
    <!-- 导出模态框 -->
    <n-modal
        v-model:show="data.show_excel"
        preset="dialog"
        title="导出提示..."
        content="导出文件正在生成中,是否前去下载中心下载"
        positive-text="立即查看"
        negative-text="过会再去"
        @positive-click="go_excel"
        @negative-click="cancelCallback"
    />


  </CommonPage>
</template>
